﻿(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/section/section.html", {
        /// <field type="WinJS.Binding.List" />
        _items: null,

        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            var listView = element.querySelector(".itemslist").winControl;
            var group = Data.resolveGroupReference(options.groupKey);
            this._items = Data.getItemsFromGroup(group);

            var searchBox = document.getElementById("searchBox").winControl;
            searchBox.addEventListener("querysubmitted", this.searchQuerySubmitted.bind(this));
            searchBox.addEventListener("querychanged", this.searchQuerySubmitted.bind(this));
            element.querySelector("header[role=banner] .pagetitle").textContent = options.title;

            this.downloadBartFeed();

            var that = this;
            BartData.FilteredStationList = BartData.StationList.createFiltered(function (item) {
                if (that.currentSearchString) {
                    if (item.Name.toUpperCase().substring(0, that.currentSearchString.length) == that.currentSearchString) {
                        return true;
                    }
                    return false;
                }
                return true;
            });

            listView.itemDataSource = BartData.FilteredStationList.dataSource;
            listView.oniteminvoked = this._itemInvoked.bind(this);
            listView.element.focus();
        },

        searchQuerySubmitted: function (eventObject) {
            this.currentSearchString = eventObject.detail.queryText.toUpperCase();
            BartData.StationList.forEach(function (n, i) { BartData.StationList.notifyMutated(i); });
        },

        unload: function () {
            this._items.dispose();
        },

        // This function updates the page layout in response to layout changes.
        updateLayout: function (element) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in layout.
        },

        _itemInvoked: function (args) {
            var station = BartData.FilteredStationList.getAt(args.detail.itemIndex);
            WinJS.Navigation.navigate("/pages/item/item.html", { item: station });
        },

        downloadBartFeed: function () {
            var stationList = new WinJS.Binding.List();

            var publicMembers = { StationList: stationList };
            WinJS.Namespace.define("BartData", publicMembers);

            WinJS.xhr({ url: "http://bart.gov/dev/eta/bart_eta.xml" }).then(function (rss) {
                if (rss.status === 200) {
                    var stations = rss.responseXML.querySelectorAll("station");

                    for (var n = 0; n < stations.length; n++) {
                        // grab station name, date, and time
                        var name = stations[n].querySelector("name").textContent;
                        var abbreviation = stations[n].querySelector("abbr").textContent;
                        var date = new Date(stations[n].querySelector("date").textContent);
                        var time = stations[n].querySelector("time").textContent;

                        var etaList = new WinJS.Binding.List();
                        // make an array of etas for the station
                        var etas = stations[n].querySelectorAll("eta");
                        for (var m = 0; m < etas.length; m++) {
                            etaList.push(
                                WinJS.Binding.as({
                                    destination: etas[m].querySelector("destination").textContent,
                                    estimate: etas[m].querySelector("estimate").textContent
                                })
                            );
                        }
                        stationList.push(WinJS.Binding.as({ Name: name, Abbreviation: abbreviation, Date: date, Time: time, ETAs: etaList }));
                    }

                }
            });
        }

    });
})();
